package com.zyy.rabbitmq.simple;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/05/18 23:38
 */
public class Consumer {
    public static void main(String[] args) {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2.设置连接属性
        connectionFactory.setHost("39.108.49.252");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //3.从连接工厂中获取连接
            connection = connectionFactory.newConnection("zyy_producer");
            //4.从连接中创建通道channel
            channel = connection.createChannel();
            /**
             * 5.声明队列queue
             * @param queue 队列的名称
             * @param durable 队列是否持久化
             * @param exclusive 是否排他，即是否私有化，如果为true，会对当前队列加锁，其他的通道不能访问，并且连接自动关闭
             * @param autoDelete 是否自动删除，当最后一个消费者断开连接之后是否自动删除消息
             * @param arguments 可以设置队列的附件参数，设置队列的有效期，消息的最大长度，队列的消息生命周期等
             */
            channel.basicConsume("zyy_queue", true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println(consumerTag + "收到的消息是" + new String(message.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String consumerTag) throws IOException {
                    System.out.println(consumerTag + "接受失败了");
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
            //7.释放连接
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}
